package com.dq.service.sys.user.centre.impl;

import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.domain.sys.user.user.centre.UserLable;
import com.dq.exception.customException.AdminException;
import com.dq.repository.BaseRepositories;
import com.dq.service.sys.user.centre.UserLableService;
import com.dq.utils.BeanNullUtil;
import com.google.gson.Gson;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;

/**
 * @author cf
 */
@Service
public class UserLableServiceImpl extends BaseRepositories implements UserLableService {

    @Override
    public UserLable save(@Valid UserLable userLable) {
        verifyObject(userLable);

        SysUser loginUser = sysUserService.getUser();
        userLable.setCreateUser(loginUser);
        userLable.setUpdateUser(loginUser);

        userLable = userLableRepository.save(userLable);
        return userLable;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserLable update(UserLable userLable) throws AdminException {
        UserLable get = dao.get(UserLable.class, userLable.getId());
        if(get == null) {
            throw new AdminException("编辑对象异常");
        }
        Gson gson = new Gson();
        UserLable update = gson.fromJson(gson.toJson(get), UserLable.class);
        BeanUtils.copyProperties(userLable, update, BeanNullUtil.getNullPropertyNames(userLable));

        verifyObject(update);

        SysUser loginUser = sysUserService.getUser();
        update.setUpdateUser(loginUser);

        update = userLableRepository.save(update);

        return update;
    }


    public void verifyObject(UserLable userLable) throws AdminException {
        if(userLable.getType() == null) {
            throw new AdminException("标签类型不明确");
        }
        UserLable get = userLableRepository.findByDeletedFalseAndNameAndType(userLable.getName(), userLable.getType());
        if(userLable.getId() == null) {
            if (get != null) {
                throw new AdminException(String.format("%s 已经存在", userLable.getName()));
            }
        }else {
            if(get != null) {
                if(!get.getId().toString().equals(userLable.getId().toString())) {
                    throw new AdminException(String.format("%s 已经存在", userLable.getName()));
                }
            }
        }
    }

}
